package com.erp.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Build
import android.util.Log
import android.view.*
import android.webkit.*
import android.widget.FrameLayout
import com.erp.mclass.LoadedListener
import com.erp.mclass.SslPinningWebViewClient
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.util.Sputil
import kotlinx.android.synthetic.main.activity_gonggaotext.*
import kotlinx.android.synthetic.main.header_knoya.view.*
import java.io.IOException





/**
 * Created by Administrator on 2017/1/11/011.
 * 作者：刘洋
 */
class GonggaoTextActivity : BaseActivity(), View.OnClickListener {

    var content = ""
    private var url: String = ""
    private var code = 0
    private var fangda=false
    private val a = "GonggaoTextActivity"
    protected val COVER_SCREEN_PARAMS = FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
    private var customView: View? = null
    private var fullscreenContainer: FrameLayout? = null
    private var customViewCallback: WebChromeClient.CustomViewCallback? = null
    override fun getLayoutId(): Int {
        activityname=a;
        return com.erp.R.layout.activity_gonggaotext
     }

    override fun initCreate() {
        code = intent.getIntExtra("code", code)
        if(code==100){
            content = intent.getStringExtra("content")
        }else {
            url = intent.getStringExtra("url")
        }
        Log.d("shouldInterceptRequest",url)
        val title = intent.getStringExtra("title")
        fangda=intent.getBooleanExtra("fangda",fangda)
        webHerder.tv_header_title.text = title
        webHerder.iv_header_left.visibility=View.VISIBLE
        webHerder.iv_header_left.setOnClickListener(this)
        initwebview()
        //移除全屏视图并隐藏
        FullVideo.removeView(webview);
        FullVideo.visibility = View.GONE;
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initwebview() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webview.settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        }
        webview.settings.javaScriptEnabled = true
        webview.settings.setSupportZoom(true)
        webview.settings.displayZoomControls = false
        webview.settings.builtInZoomControls = true
        webview.settings.domStorageEnabled = true;
        webview.settings.databaseEnabled = true;
        webview.settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN;//自适应屏幕
        if(fangda) {
            webview.addJavascriptInterface(object : JsCallJavaObj {
                @JavascriptInterface
                override fun showBigImg(url: String) {
                    val intent = Intent(this@GonggaoTextActivity, ChaKanTuZhiAvtivity::class.java)
                    val urls : ArrayList<String> = ArrayList()
                    urls.add(url)
                    intent.putStringArrayListExtra("url", urls)
                    startActivity(intent)
                }

            }, "jsCallJavaObj")
        }
        var webViewClient: SslPinningWebViewClient? = null
        try {
            webViewClient = SslPinningWebViewClient(this, object : LoadedListener {
                override fun Loaded(url: String) {
                    runOnUiThread { Log.d("TAAAAG", url) }
                }

                override fun PinningPreventedLoading(host: String) {
                    runOnUiThread { }
                }
            },webview)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        webview.webViewClient = webViewClient

        synCookies(this, url)
        if(code==100){
            webview.loadData(content, "text/html; charset=UTF-8", null);
        }else {
            webview.loadUrl(url)
        }
        webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) =
                    if (newProgress == 100) {
                        webviewPb.visibility = View.GONE
                    } else {
                        webviewPb.progress = View.VISIBLE
                        webviewPb.progress = newProgress
                    }

            override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
                showCustomView(view, callback)
            }

            override fun onHideCustomView() {
                hideCustomView()
            }

        }
        webview.setDownloadListener { url, userAgent, contentDisposition, mimetype, contentLength ->
            Log.d("setDownloadListener","url="+url)
            Log.d("setDownloadListener","userAgent="+userAgent)
            Log.d("setDownloadListener","contentDisposition="+contentDisposition)
            Log.d("setDownloadListener","mimetype="+mimetype)
            PermissionUtils.isupdate(this@GonggaoTextActivity, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    Dialogutil.downloaddialog(url, this@GonggaoTextActivity)
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法下载")
                }
            })
        }

    }

    override fun onClick(v: View?) {
        when(v){
            webHerder.iv_header_left -> {
                finish()
            }
        }
    }
    public override fun onPause() {
        super.onPause()
        webview.onPause()
        webview.pauseTimers()
    }

    public override fun onResume() {
        super.onResume()
        webview.resumeTimers()
        webview.onResume()
    }

    override fun onDestroy() {
        if (webview != null) {
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            webview.clearHistory()
            val view = window.decorView as ViewGroup
            view.removeAllViews()
            webview.destroy()
        }
        super.onDestroy()
    }


//    override fun onDestroy() {
//        webview.destroy()
//        super.onDestroy()
//    }

    fun synCookies(context: Context, url: String?) {
        Log.d("TAAAG",Sputil.sp("erp").getString("cookie", ""))
        CookieSyncManager.createInstance(context)
        val cookieManager = CookieManager.getInstance()
        cookieManager.setAcceptCookie(true)
        cookieManager.removeSessionCookie()//移除
        cookieManager.setCookie(url, Sputil.sp("erp").getString("cookie", ""))//cookies是在HttpClient中获得的cookie
        CookieSyncManager.getInstance().sync()
    }

//    override fun finish() {
//        val view = window.decorView as ViewGroup
//        view.removeAllViews()
//        super.finish()
//    }

    /**
     * Js調用Java接口
     */
    private interface JsCallJavaObj {
        fun showBigImg(url: String)
    }

    /** 视频播放全屏  */
    private fun showCustomView(view: View?, callback: WebChromeClient.CustomViewCallback?) {
        // if a view already exists then immediately terminate the new one
        if (customView != null) {
            callback!!.onCustomViewHidden()
            return
        }
        Log.d("GGGWEBVIEW","showCustomView")
        this@GonggaoTextActivity.window.getDecorView()

        val decor = window.decorView as FrameLayout
        fullscreenContainer = FullscreenHolder(this@GonggaoTextActivity)
        fullscreenContainer!!.addView(view, COVER_SCREEN_PARAMS)
        decor.addView(fullscreenContainer, COVER_SCREEN_PARAMS)
        customView = view
        setStatusBarVisibility(false)
        customViewCallback = callback
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;//设置横屏
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置全屏
    }

    /** 隐藏视频全屏  */
    private fun hideCustomView() {
        if (customView == null) {
            return
        }

        setStatusBarVisibility(true)
        val decor = window.decorView as FrameLayout
        decor.removeView(fullscreenContainer)
        fullscreenContainer = null
        customView = null
        customViewCallback!!.onCustomViewHidden()
        webview.visibility = View.VISIBLE
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT//设置竖屏
        window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)//清除全屏
    }

    /** 全屏容器界面  */
    internal class FullscreenHolder(ctx: Context) : FrameLayout(ctx) {

        init {
            setBackgroundColor(ctx.getResources().getColor(android.R.color.black))
        }

        override fun onTouchEvent(evt: MotionEvent): Boolean {
            return true
        }
    }

    private fun setStatusBarVisibility(visible: Boolean) {
        val flag = if (visible) 0 else WindowManager.LayoutParams.FLAG_FULLSCREEN
        window.setFlags(flag, WindowManager.LayoutParams.FLAG_FULLSCREEN)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_BACK -> {
                /** 回退键 事件处理 优先级:视频播放全屏-网页回退-关闭页面  */
                if (customView != null) {
                    hideCustomView()
                } else if (webview.canGoBack()) {
                    webview.goBack()
                } else {
                    finish()
                }
                return true
            }
            else -> return super.onKeyUp(keyCode, event)
        }
    }

}
